<?php
require_once 'CMS/Util.php';
require_once 'CMS/User.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseAdminController.php';
require_once 'CMS/AdminCommon.php';

//Người tạo : Huỳnh Trọng Hiếu
//Module 	: editor
//Chức năng	: editor

class Admin_EditorController extends BaseAdminController {
		
	public function init(){
		parent::init();
		$this->_helper->layout()->setLayout('layoutadmin');
		$user = new User();
		$user->init();
		$user->check_login();
		//$user->permission();
	}
	
	public function indexAction(){
		$this->_helper->layout->disableLayout();
		$session = new Zend_Session_Namespace('block.auth');
		/* -------------- Start Xu ly load db  ---------------- */
		$tbLanguage = new Language_Model_Language();
		$Languages = $tbLanguage->getAllLanguages();
		if(isset($_GET['step'])&&($_GET['step']==0))
		{
			$session->block = array();
		}
		if(isset($_GET['step'])&&(is_numeric($_GET['step']))&&($_GET['step']<=(count($Languages))))
		{
			if($_GET['step']==0)
			{
				$this->view->language = "Default";
			} 
			else
			{
				$this->view->language = $Languages[$_GET['step']-1]['name'];
			}
		}
		if(!isset($_SESSION['delete_image']))
		{
			if(isset($_GET['item']))
			{
				$_SESSION['item'] = $_GET['item'];
				if(isset($_GET['step'])&&(is_numeric($_GET['step']))&&($_GET['step']<=(count($Languages))))
				{
					  $_SESSION['step_edit'] = $_GET['step'];
					  if(isset($_GET['id'])&&(is_numeric($_GET['id']))&&($_GET['id']>0))
					  {
					  	 $_SESSION['edit_thing'] = $_GET['id'];
					  	 $tbThing = new User_Model_Things();
					  	 $Description = $tbThing->getThingById($_GET['id']);
					  	 if(count($Description)>0)
					  	 {
					  	 	if(count($Description[0]['description_table'])>0&&($Description[0]['description_table']!="")&&($Description[0]['description_table']!=null))
					  	 	{
					  	 		$temp = unserialize($Description[0]['description_table']) ;
					  	 		if($_GET['step']==0)
					  	 		{
					  	 			$session->block = $temp["Default"];
					  	 			$this->view->language = "Default";
					  	 		}
					  	 		else
					  	 		{
					  	 			$session->block = $temp[$Languages[$_GET['step']-1]['name']];
					  	 		}
					  	 	}
					  	 	else
					  	 	{
					  	 		$session->block = null;
					  	 	}
					  	 }
					  	 else {
					  	 	$this->view->error = 1;
					  	 }
					  }
					  else if (isset($_GET['page']))
					  {
					     $_SESSION['edit_page'] = $_GET['page'];
					  	 $tbCurrentPage = new Admin_Model_CurrentPage();
					  	 $page = $tbCurrentPage->selectPageByCode($_GET['page']);
					  	 if(count($page)>0)
					  	 {
					  	 	if(count($page[0]['description_table'])>0&&($page[0]['description_table']!="")&&($page[0]['description_table']!=null))
					  	 	{
					  	 		$temp = unserialize($page[0]['description_table']) ;
					  	 		if($_GET['step']==0)
					  	 		{
					  	 			$session->block = $temp["Default"];
					  	 		}
					  	 		else
					  	 		{
					  	 			$session->block = $temp[$Languages[$_GET['step']-1]['name']];
					  	 		}
					  	 	}
					  	 	else
					  	 	{
					  	 		$session->block = null;
					  	 	}
					  	 }
					  	 else {
					  	 	$this->view->error = 1;
					  	 }
					  }
				}
				else
				{
					$this->view->error = 1;
				}
			}
			else
			{
				$this->view->error = 1;
			}
		}
		else
		{
			unset($_SESSION['delete_image']);
		}
		/* -------------- End Xu ly load db  ------------------ */
		if($session->temp['type']==1) // gan data cho block text
			$session->block[$session->temp['id']]['data'] = str_replace(array("\r\n", "\n", "\r"), '', trim($session->temp['data']));
		
		if($session->temp['type']==2) // gan data cho block image
			$session->block[$session->temp['id']]['image'][$session->temp['id_image']] = $session->temp['data'];

		if($session->temp['type']==3) // gan data cho block table
		{
			$table = str_replace(array("\r\n", "\n", "\r"), '', trim($session->temp['data']));
			if(!strpos($table, '</tr>'))
				$table = '<table width="100%" cellspacing="0" cellpadding="4" border="1"><tbody><tr><td>'.$table.'</td></tr></tbody></table>';
			
			$session->block[$session->temp['id']]['data'] = $table;
		}
		
		unset($session->temp);			   
	   
	    for($i=1;$i<=sizeof($session->block)-1;$i++)
	    	for($j=$i+1;$j<=sizeof($session->block);$j++)
	    	{
	    		if($session->block[$i-1]['sort'] > $session->block[$j-1]['sort'] || isset($session->block[$i-1]['deleted']))
	    		{
	    			$temp = $session->block[$i-1];
	    			$session->block[$i-1] = $session->block[$j-1];
	    			$session->block[$j-1] = $temp;
	    		}
	    	}
	    
	    for($i=1;$i<=sizeof($session->block);$i++)
	    {
	    	$session->block[$i-1]['sort'] = $i;
	    	if(isset($session->block[$i-1]['deleted']))
	    	{
	    		unset($session->block[$i-1]);
	    	}
	    }
	    if($session->block!="")
	    	$session->block = array_values($session->block);
	    
		if($_GET['reset'] == 1)
			unset($session->block);
		$block = $session->block;
			
		if($_GET['type'] == 1) // them cho block text
			$block[] = array( 
				'type' => 1,
				'data' => "Click Here To Edit Text !",
				'sort' => sizeof($session->block)+1
			);
		if($_GET['type'] == 2) // them cho block image
			$block[$_GET['image']-1]['image'][] = array( 
							'src' => '/images/noimage.jpg',
							'alt' => '',
							'width' => '100',
							'height'=> '100',
							'border'=> '',
							'hspace'=> '5',
							'vspace'=> '5',
							'align'=> '0',
							'url'=> '',
							'target'=> ''
			);
		if($_GET['type'] == 3) // them cho block table
		{
			$table = str_replace(array("\r\n", "\n", "\r"), '', trim($_GET["table"]));
			if(!strpos($table, '</tr>'))
				$table = '<table width="100%" cellspacing="0" cellpadding="4" border="1"><tbody><tr><td>&nbsp;</td></tr></tbody></table>';
			
			$block[] = array( 
				'type' => 3,
				'data' => $table,
				'sort' => sizeof($session->block)+1
			);
		}
			
		if($_GET['type'] == 4) // them cho block break
			$block[] = array( 
				'type' => 4,
				'data' => '<hr style=\"width: 100%; height: 1px;margin-top:2px;margin-bottom:2px;background-color:black;opacity:1;clear:both;\">',
				'sort' => sizeof($session->block)+1
			);
					
		if($block == null) $block = array();
		$session->block = $block;
		
		
		if($_GET['type'] == -1) // Xu ly preview
			$this->_redirect('/index/preview');
		/* -------------- Start Xu ly luu db  ---------------- */
		// du lieu db = $session 
		if($_GET['type'] == -2)
		{
			$tbLanguage = new Language_Model_Language();
			$Languages = $tbLanguage->getAllLanguages();
			if(isset($_SESSION['step_edit'])&&(is_numeric($_SESSION['step_edit']))&&($_SESSION['step_edit']>=0)&&($_SESSION['step_edit']<=(count($Languages)+1)))
			{
				if(isset($_SESSION['item'])&&($_SESSION['item']=="thing"))
				{
					$tbThing = new User_Model_Things();
					$description_thing = array();
					$description_table_thing = array();
					if(isset($_SESSION['description_thing']))
					{
						$description_thing = $_SESSION['description_thing'];
					}
					else if (isset($_SESSION['edit_thing'])&&(is_numeric($_SESSION['edit_thing']))&&($_SESSION['edit_thing'])>0)
					{
						$thing = $tbThing->getThingById($_SESSION['edit_thing']);
						$description_thing = unserialize($thing[0]['description']);
					}
					else
					{
						$description_thing['Default'] = "";
						foreach($Languages as $lang)
						{
							$description_thing[$lang['name']] = "";
						}
					}
					if(isset($_SESSION['description_table_thing']))
					{
						$description_table_thing = $_SESSION['description_table_thing'];
					}
					else if (isset($_SESSION['edit_thing'])&&(is_numeric($_SESSION['edit_thing']))&&($_SESSION['edit_thing']>0))
					{
						$thing = $tbThing->getThingById($_SESSION['edit_thing']);
						$description_table_thing = unserialize($thing[0]['description_table']);
					}
					else
					{
						$description_table_thing['Default'] = "";
						foreach($Languages as $lang)
						{
							$description_table_thing[$lang['name']] = "";
						}
					}
					
						$new_description = array();
						$new_description_table = array();
						$i = 0;
						$j = 0;
						foreach($description_thing as $lang => $value)
						{
							if($i == $_SESSION['step_edit'])
							{
								$j++;
								if($i==0)
								{
									$new_description["Default"] = Util::html_editor();
								}
								else 
								{
									$new_description[$Languages[$i-1]['name']] = Util::html_editor();
								}
								$i++;
							}
							else
							{
								if($i==0)
								{
									$new_description["Default"] = $value;
								}
								else 
								{
									$new_description[$Languages[$i-1]['name']] = $value;
								}
								$i++;
							}
						}
						if($j == 0)
						{
							$new_description[$Languages[$_SESSION['step_edit']-1]['name']] = Util::html_editor();
						}
						$i = 0;
						$j = 0;
						foreach($description_table_thing as $lang => $value)
						{
							if($i == $_SESSION['step_edit'])
							{
								$j++;
								if($i==0)
								{
									$new_description_table["Default"] =$session->block;
								}
								else 
								{
									$new_description_table[$Languages[$i-1]['name']] = $session->block;
								}
								$i++;
							}
							else
							{
								if($i==0)
								{
									$new_description_table["Default"] = $value;
								}
								else 
								{
									$new_description_table[$Languages[$i-1]['name']] = $value;
								}
								$i++;
							}
						}
						if($j == 0)
						{
							$new_description_table[$Languages[$_SESSION['step_edit']-1]['name']] = $session->block;
						}
						if($_SESSION['step_edit'] == (count($Languages)))
						{
							if(isset($_SESSION['array_news_data']))
							{
								//if thing == news
								$insertData = $_SESSION['array_news_data'];
								$insertData['description'] = serialize($new_description);
								$insertData['description_table'] = serialize($new_description_table);
								if(isset($_SESSION['edit_thing'])&&(is_numeric($_SESSION['edit_thing']))&&($_SESSION['edit_thing']>0))
								{
									$tbThing->updateThing($_SESSION['edit_thing'], $insertData);
								}
								else
								{
									$tbThing->insertThings($insertData);
								}
								unset($_SESSION['array_news_data']);
							}
							else
							{
								//if thing == product
								$data = array(
									"description" => serialize($new_description),
									"description_table" => serialize($new_description_table),
									"update_date"	=>Util::get_time_now()
								);
								$tbThing->updateThing($_SESSION['edit_thing'],$data);
							}
							unset($_SESSION['edit_thing']);
							unset($_SESSION['description_thing']);
							unset($_SESSION['description_table_thing']);
							unset($_SESSION['item']);
							unset($_SESSION['step_edit']);
							$session->block = array();
							$_SESSION['success'] = 1;
						}
						else
						{
							$_SESSION['description_thing'] = $new_description;
							$_SESSION['description_table_thing'] = $new_description_table;
							$session->block = array();
							if(isset($_SESSION['edit_thing'])&&(is_numeric($_SESSION['edit_thing']))&&($_SESSION['edit_thing']>0))
							{
								$this->_redirect("/admin/editor?item=thing&step=".($_SESSION['step_edit']+1)."&id=".$_SESSION['edit_thing']);
							}
							else
							{
								$this->_redirect("/admin/editor?item=thing&step=".($_SESSION['step_edit']+1));
							}
						}
				}
				else if(isset($_SESSION['item'])&&($_SESSION['item']=="page"))
				{
					$tbCurrentPage = new Admin_Model_CurrentPage();
					$description_page = array();
					$description_table_page = array();
					if(isset($_SESSION['description_page']))
					{
						$description_page = $_SESSION['description_page'];
					}
					else if (isset($_SESSION['edit_page']))
					{
						$page = $tbCurrentPage->selectPageByCode($_SESSION['edit_page']);
						$description_page = unserialize($page[0]['description']);
					}
					else
					{
						$description_page['Default'] = "";
						foreach($Languages as $lang)
						{
							$description_page[$lang['name']] = "";
						}
					}
					if(isset($_SESSION['description_table_page']))
					{
						$description_table_page = $_SESSION['description_table_page'];
					}
					else if (isset($_SESSION['edit_page']))
					{
						$page = $tbCurrentPage->selectPageByCode($_SESSION['edit_page']);
						$description_table_page = unserialize($page[0]['description_table']);
					}
					else
					{
						$description_table_page['Default'] = "";
						foreach($Languages as $lang)
						{
							$description_table_page[$lang['name']] = "";
						}
					}
					$new_description = array();
					$new_description_table = array();
					$i = 0;
					$j = 0;
					foreach($description_page as $lang => $value)
					{
						if($i == $_SESSION['step_edit'])
						{
							$j++;
							if($i==0)
							{
								$new_description["Default"] = Util::html_editor();
							}
							else 
							{
								$new_description[$Languages[$i-1]['name']] = Util::html_editor();
							}
							$i++;
						}
						else
						{
							if($i==0)
							{
								$new_description["Default"] = $value;
							}
							else 
							{
								$new_description[$Languages[$i-1]['name']] = $value;
							}
							$i++;
						}
					}
					if($j == 0)
					{
						$new_description[$Languages[$_SESSION['step_edit']-1]['name']] = Util::html_editor();
					}
					$i = 0;
					$j = 0;
					foreach($description_table_page as $lang => $value)
					{
						if($i == $_SESSION['step_edit'])
						{
							$j++;
							if($i==0)
							{
								$new_description_table["Default"] =$session->block;
							}
							else 
							{
								$new_description_table[$Languages[$i-1]['name']] = $session->block;
							}
							$i++;
						}
						else
						{
							if($i==0)
							{
								$new_description_table["Default"] = $value;
							}
							else 
							{
								$new_description_table[$Languages[$i-1]['name']] = $value;
							}
							$i++;
						}
					}
					if($j == 0)
					{
						$new_description_table[$Languages[$_SESSION['step_edit']-1]['name']] = $session->block;
					}
					if($_SESSION['step_edit'] == (count($Languages)))
					{
						if(isset($_SESSION['array_page_data']))
						{						
							$insertData = $_SESSION['array_page_data'];
							$insertData['description'] = serialize($new_description);
							$insertData['description_table'] = serialize($new_description_table);
							if(isset($_SESSION['edit_page']))
							{
								$page = $tbCurrentPage->selectPageByCode($_SESSION['edit_page']);
								$tbCurrentPage->updatePropertiesCurrentPage($page[0]['page_code'], $insertData);
									$data_2 = array(
										'page_code'=>$insertData['page_code'],		
									);
								$tbContentModuleToPage = new Admin_Model_ContentModuleToPage();
								$tbContentModuleToPage->updatePageCodeByCode($page[0]['page_code'],$data_2);
							}
							else
							{
								$tbCurrentPage->insertCurrentPage($insertData);
							}
							unset($_SESSION['array_page_data']);
						}
						else
						{
							$thi->view->error = 1;
						}
						unset($_SESSION['edit_page']);
						unset($_SESSION['description_page']);
						unset($_SESSION['description_table_page']);
						unset($_SESSION['item']);
						unset($_SESSION['step_edit']);
						$session->block = array();
						$_SESSION['success'] = 1;
					}
					else
					{
						$_SESSION['description_page'] = $new_description;
						$_SESSION['description_table_page'] = $new_description_table;
						$session->block = array();
						if(isset($_SESSION['edit_page']))
						{
							$this->_redirect("/admin/editor?item=page&step=".($_SESSION['step_edit']+1)."&page=".$_SESSION['edit_page']);
						}
						else
						{
							$this->_redirect("/admin/editor?item=page&step=".($_SESSION['step_edit']+1));
						}
					}
				}			
			}
		}	
		/* -------------- End Xu ly luu db  ------------------ */ 
		if(isset($_GET["type"]) || isset($_GET["reset"])) 
		{

				$this->_redirect('/admin/editor');
		}
		$this->view->block = $block;
	}
	
	public function deleteblockAction(){
		$session = new Zend_Session_Namespace('block.auth');
		if(isset($_GET["id"]))
		{
			$session->block[$_GET["id"]-1]['deleted'] = 1;
		}
		$this->_helper->json('');
	}
	
	public function deleteimageblockAction(){
		$session = new Zend_Session_Namespace('block.auth');
		if(isset($_GET["i"])&&isset($_GET["j"]))
		{
			$session->block[$_GET["i"]-1]['image'][$_GET["j"]-1] = "";
			$_SESSION['delete_image'] = 1;
		}
		$this->_helper->json('');
	}
	
	public function sortblockAction(){
		$session = new Zend_Session_Namespace('block.auth');
		$session->block[$_GET["i1"]-1]['sort'] = $_GET["sort1"];
		$session->block[$_GET["i2"]-1]['sort'] = $_GET["sort2"];
		$this->_helper->json('');
	}
	
	public function saveblockAction(){
		$session = new Zend_Session_Namespace('block.auth');
		$session->temp['id'] = (isset($_GET['i'])?$_GET['i']:"") - 1;
		$session->temp['id_image'] = (isset($_GET['j'])?$_GET['j']:"") - 1;
		$session->temp['data'] = isset($_GET['data'])?$_GET['data']:"";
		$session->temp['type'] = isset($_GET['type'])?$_GET['type']:"";
		$this->_helper->json('');
	}
	
	public function editortextAction(){
		$this->_helper->layout->disableLayout();
		$this->view->data = isset($_GET['data'])?$_GET['data']:"";
		$this->view->i = isset($_GET['i'])?$_GET['i']:"";
	}
	
	public function editorimageAction(){
		$this->_helper->layout->disableLayout();
		$this->view->data = isset($_GET['data'])?$_GET['data']:"";
		$this->view->i = isset($_GET['i'])?$_GET['i']:"";
		$this->view->j = isset($_GET['j'])?$_GET['j']:"";
	}
	
	public function editortableAction(){
		$this->_helper->layout->disableLayout();
		$this->view->data = isset($_GET['data'])?$_GET['data']:"";
		$this->view->i = isset($_GET['i'])?$_GET['i']:"";
	}
}